package com.hai.mediapicker.activity;

import android.Manifest;
import android.animation.AnimatorSet;
import android.animation.ObjectAnimator;
import android.annotation.TargetApi;
import android.content.Intent;
import android.content.DialogInterface;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.graphics.Point;
import android.hardware.Camera;
import android.media.AudioManager;
import android.media.CamcorderProfile;
import android.media.MediaPlayer;
import android.media.MediaRecorder;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.annotation.SuppressLint;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.MotionEvent;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.view.WindowManager;
import android.widget.RelativeLayout;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.hai.mediapicker.R;
import com.hai.mediapicker.entity.Photo;
import com.hai.mediapicker.util.SDKUtil;
import com.hai.mediapicker.util.MediaManager;
import com.hai.mediapicker.util.GalleryFinal;
import com.hai.mediapicker.util.MemoryLeakUtil;
import com.hai.mediapicker.view.RecordedButton;
import com.hai.mediapicker.view.RingProgress;

import org.greenrobot.eventbus.EventBus;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;
import java.util.Timer;
import java.util.TimerTask;

/**
 * Created by Administrator on 2017/6/12.
 */

public class CaptureActivity extends AppCompatActivity implements View.OnClickListener {

    public static final String TAG = "VideoLog-naonao";
    private static final int HANDLER_RECORD = 200;
    private static final int CUT_VIDEO_CODE = 444;

    android.hardware.Camera camera;
    SurfaceView surfaceView;
    int facing = Camera.CameraInfo.CAMERA_FACING_BACK, cameraId;
    String fileType;
    RelativeLayout rlDecide;
    RecordedButton rlStart;
    byte[] data;
    MediaRecorder mMediaRecorder;
    String videoPath;
    Point bestSize;
    MediaPlayer mediaplayer;
    View viewSave;

	private TextView tvHint;
    private ImageView ivChangeFlash;
    private ImageView ivChangeCamera;
    private ImageView ivCutTime;
    private ImageView rbClose;
    private boolean isFlash;
	private boolean isRecordedOver;

    long start;
    long end;
    int maxDuration = 11000;//最多只能录视频的时间长度

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        maxDuration = getIntent().getIntExtra("maxDuration", 11 * 1000);
        fileType = getIntent().getStringExtra("fileType");
        initUi();
    }

    private void initUi() {
        WindowManager.LayoutParams winParams = getWindow().getAttributes();
        winParams.flags |= WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION;
        winParams.flags |= WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS;
        getWindow().setAttributes(winParams);

        setContentView(R.layout.activity_capture);
        surfaceView = (SurfaceView) findViewById(R.id.surface_capture);
        surfaceView.setFocusableInTouchMode(true);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
            surfaceView.setSecure(true);
        }
		tvHint = (TextView) findViewById(R.id.tv_hint);
        ivChangeFlash = (ImageView) findViewById(R.id.iv_change_flash);
        ivChangeCamera = (ImageView) findViewById(R.id.iv_change_camera);
        ivCutTime = (ImageView) findViewById(R.id.iv_cut_time);
        rlDecide = (RelativeLayout) findViewById(R.id.rl_decide);
        rlStart = (RecordedButton) findViewById(R.id.rb_start);
        rbClose = (ImageView) findViewById(R.id.rb_close);
        viewSave = findViewById(R.id.iv_save);
        findViewById(R.id.iv_cancel).setOnClickListener(this);
        findViewById(R.id.iv_ok).setOnClickListener(this);
        ivCutTime.setOnClickListener(this);
        viewSave.setOnClickListener(this);

        if(!"3".equals(fileType)) {
            tvHint.setText("点击拍照");
        }
        surfaceView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (camera != null)
                    camera.autoFocus(null);
            }
        });

        rlStart.setMax(maxDuration);
        rlStart.setOnGestureListener(new RecordedButton.OnGestureListener() {
            @Override
            public void onLongClick() {
                if("3".equals(fileType)) {
                    isRecordedOver = false;
                    prepareVideoRecorder();
                    rlStart.setSplit();
                    myHandler.sendEmptyMessageDelayed(HANDLER_RECORD, 50);
                }
            }
            @Override
            public void onClick() {
				takePicture();
            }
            @Override
            public void onLift() {
                if("3".equals(fileType)) {
                    isRecordedOver = true;
                    rlStart.setProgress(0);
                    rlStart.cleanSplit();
                    endRecord();
                }
            }
            @Override
            public void onOver() {
                if("3".equals(fileType)) {
                    isRecordedOver = true;
                    rlStart.setProgress(0);
                    rlStart.cleanSplit();
                    rlStart.closeButton();
                    if(mMediaRecorder != null) {
                        stopRecord();
                    }
                }
            }
        });

        rbClose.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });

        surfaceView.getHolder().addCallback(new SurfaceHolder.Callback() {
            @Override
            public void surfaceChanged(SurfaceHolder holder, int format, final int width, final int height) {
                if (holder.getSurface() == null)
                    return;

            }

            @Override
            public void surfaceCreated(SurfaceHolder holder) {
                holder.setKeepScreenOn(true);
                holder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
                startPreview(-1, isFlash);
            }

            @Override
            public void surfaceDestroyed(SurfaceHolder holder) {
                stopPreview();
            }
        });

        ivChangeCamera.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                int numberOfCameras = Camera.getNumberOfCameras();
                Camera.CameraInfo cameraInfo = new Camera.CameraInfo();
                for (int i = 0; i < numberOfCameras; i++) {
                    Camera.getCameraInfo(i, cameraInfo);
                    if (cameraInfo.facing != facing) {
                        stopPreview();
                        if(i == 1) {
                            ivChangeFlash.setImageResource(R.mipmap.video_flash_close);
                            isFlash = false;
                        }
                        startPreview(i, isFlash);
                        facing = cameraInfo.facing;
                        cameraId = i;
                        break;
                    }
                }
            }
        });

        ivChangeFlash.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(cameraId == 0) {
                    if(!isFlash) {
                        isFlash = true;
                        startPreview(cameraId, isFlash);
                        ivChangeFlash.setImageResource(R.mipmap.video_flash_open);
                    }else {
                        isFlash = false;
                        startPreview(cameraId, isFlash);
                        ivChangeFlash.setImageResource(R.mipmap.video_flash_close);
                    }
                }
            }
        });

        checkPermission();
    }

    @SuppressLint("HandlerLeak")
    private Handler myHandler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            switch(msg.what) {
                case HANDLER_RECORD: {
                        if(!isRecordedOver) {
                            rlStart.setProgress(System.currentTimeMillis() - start);
                            myHandler.sendEmptyMessageDelayed(HANDLER_RECORD, 30);
                        }
                    }
					break;
			}
		}
	};

    private void checkPermission() {
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
            return;
        }
        String[] permissions = {
                Manifest.permission.CAMERA,
                Manifest.permission.RECORD_AUDIO,
                Manifest.permission.WRITE_EXTERNAL_STORAGE,
                Manifest.permission.READ_EXTERNAL_STORAGE
        };
        ArrayList<String> needRequestPermission = new ArrayList<>();
        for (int i = 0; i < permissions.length; i++) {
            if (checkSelfPermission(permissions[i]) != PackageManager.PERMISSION_GRANTED) {
                needRequestPermission.add(permissions[i]);
            }
        }
        if (!needRequestPermission.isEmpty()) {
            requestPermissions(needRequestPermission.toArray(new String[needRequestPermission.size()]), 11);
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        startPreview(-1, isFlash);
    }

    public void startPreview(int _cameraId, boolean isFlash) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && checkSelfPermission(Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
            return;
        }

        if (_cameraId == -1) {
            int numberOfCameras = Camera.getNumberOfCameras();
            if (numberOfCameras == 0) {
                new AlertDialog.Builder(CaptureActivity.this)
                        .setTitle(getString(R.string.error_camera_title))
                        .setCancelable(false)
                        .setMessage(getString(R.string.error_no_camera))
                        .setPositiveButton(getString(R.string.btn_ok), new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                finish();
                            }
                        })
                        .create().show();
                return;
            }
            Camera.CameraInfo cameraInfo = new Camera.CameraInfo();
            for (int i = 0; i < numberOfCameras; i++) {
                Camera.getCameraInfo(i, cameraInfo);
                if (cameraInfo.facing == Camera.CameraInfo.CAMERA_FACING_BACK) {
                    facing = cameraInfo.facing;
                    cameraId = i;
                    break;
                }
            }
        } else
            cameraId = _cameraId;
        try {
            camera = android.hardware.Camera.open(cameraId);
            camera.setDisplayOrientation(90);
            camera.setPreviewDisplay(surfaceView.getHolder());
            DisplayMetrics displayMetrics = new DisplayMetrics();
            getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);
            android.hardware.Camera.Parameters parameters = camera.getParameters();
            bestSize = getBestCameraResolution(parameters, new Point(displayMetrics.widthPixels, displayMetrics.heightPixels));

            Point bestPictureSize = getBestCameraResolution(parameters.getSupportedPictureSizes(), new Point(displayMetrics.widthPixels, displayMetrics.heightPixels));

            parameters.setPreviewSize(bestSize.x, bestSize.y);
            parameters.setPictureSize(bestPictureSize.x, bestPictureSize.y);
            if (parameters.getSupportedFocusModes().contains(Camera.Parameters.FOCUS_MODE_AUTO))
                parameters.setFocusMode(Camera.Parameters.FOCUS_MODE_AUTO);

            parameters.setFocusMode(Camera.Parameters.FOCUS_MODE_CONTINUOUS_VIDEO);
            if (isFlash) {
				parameters.setFlashMode(android.hardware.Camera.Parameters.FLASH_MODE_TORCH);
            }else {
                parameters.setFlashMode(android.hardware.Camera.Parameters.FLASH_MODE_OFF);
			}
            camera.setParameters(parameters);
            camera.startPreview();
        } catch (Exception e) {
            e.printStackTrace();
            if (camera != null) {
                camera.stopPreview();
                camera.release();
                camera = null;
            }
        }
        if (camera == null) {
            new AlertDialog.Builder(CaptureActivity.this)
                    .setTitle(getString(R.string.error_camera_title))
                    .setCancelable(false)
                    .setMessage(getString(R.string.error_open_camera))
                    .setPositiveButton(getString(R.string.btn_ok), new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            finish();
                        }
                    })
                    .create().show();
            return;
        }
    }

    public void stopPreview() {
        if (camera == null)
            return;
        camera.stopPreview();
        camera.setPreviewCallback(null);
        camera.release();
        camera = null;
    }

    private Point getBestCameraResolution(Camera.Parameters parameters, Point screenResolution) {
        float tmp = 0f;
        float mindiff = 100f;
        float x_d_y = (float) screenResolution.x / (float) screenResolution.y;
        android.hardware.Camera.Size best = null;
        List<android.hardware.Camera.Size> supportedPreviewSizes = parameters.getSupportedPreviewSizes();

        for (android.hardware.Camera.Size s : supportedPreviewSizes) {
            tmp = Math.abs(((float) s.height / (float) s.width) - x_d_y);
            if (tmp < mindiff) {
                mindiff = tmp;
                best = s;
            }
        }
        return new Point(best.width, best.height);
    }


    /**
     * 我的选择策略：找到最接近屏幕尺寸的尽量大的哪一个尺寸，如果没有比它大的就选择支持的最大的,
     *
     * @param supportedSizes
     * @param screenResolution
     * @return
     */
    private Point getBestCameraResolution(List<android.hardware.Camera.Size> supportedSizes, Point screenResolution) {
        Camera.Size bestFitSize = null;
        if (supportedSizes.size() > 0)
            bestFitSize = supportedSizes.get(supportedSizes.size() - 1);

        for (int i = supportedSizes.size() - 2; i >= 0; i--) {

            /**本来是应该比较supportedSizes.get(i).width的，但是获取到的尺寸高度是正常的宽度*/
            if (screenResolution.x == supportedSizes.get(i).height
                    && supportedSizes.get(i).height == (supportedSizes.get(i).width * 3 / 4)) {

                bestFitSize = supportedSizes.get(i);
                break;
            }
        }

        if (bestFitSize == null)
            return screenResolution;

        return new Point(bestFitSize.width, bestFitSize.height);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        GalleryFinal.mOnCaptureListener = null;
        MemoryLeakUtil.fixInputMethodManagerLeak(this);
    }

    private void clearVideoFile() {
        if (videoPath == null)
            return;
        File file = new File(videoPath);
        if (file.exists())
            file.delete();
    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
        justStopRecord();
        stopVideo();
        clearVideoFile();
    }

    @Override
    protected void onPause() {
        super.onPause();
        stopVideo();
    }

    @Override
    protected void onResume() {
        super.onResume();
    }

    @Override
    public void onClick(View v) {
        if (v.getId() == R.id.iv_cancel) {
            data = null;
            showStart();
            stopVideo();
            startPreview(cameraId, isFlash);

            clearVideoFile();
        } else if (v.getId() == R.id.iv_ok) {
            if (data != null)
                savePictureAsync(data, camera);
            else
                saveVideo();
        } else if (v.getId() == R.id.iv_cut_time) {
            Intent intent = new Intent(this, CutTimeActivity.class);
            intent.putExtra("path", videoPath);
            intent.putExtra("cutType", 1);
            startActivityForResult(intent, CUT_VIDEO_CODE);
        } else if (v.getId() == R.id.iv_save) {
			v.setVisibility(View.GONE);
            if(mediaplayer != null) {
                if(mediaplayer.isPlaying()) {
                    mediaplayer.stop();
                }
                mediaplayer.start();
            }
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if(requestCode == CUT_VIDEO_CODE && resultCode == RESULT_OK) {
			Photo photo = new Photo();
			photo.setPath(data.getStringExtra("videoPath"));
            photo.setDuration(1000);
            send(photo);
            finish();
        }
    }

    private void saveMedia() {
        new AsyncTask<Void, Void, Boolean>() {

            @Override
            protected Boolean doInBackground(Void... params) {
                String file = "";
                if (data != null) {
                    try {
                        Photo photo = savePicture(data, camera);
                        file = photo.getPath();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
                return GalleryFinal.getSaver().save(file);
            }

            @Override
            protected void onPostExecute(Boolean bool) {
                super.onPostExecute(bool);
            }
        }.execute();
    }

    private void takePicture() {
        if (camera == null)
            return;
        try {
            camera.takePicture(null, null, new Camera.PictureCallback() {
                @Override
                public void onPictureTaken(byte[] data, Camera camera) {
                    CaptureActivity.this.data = data;
                    stopPreview();
                    showDecide();
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void saveVideo() {
        int duration = mediaplayer != null ? mediaplayer.getDuration() : 0;
        stopVideo();
        Photo photo = new Photo();
        photo.setWidth(bestSize.x);
        photo.setHeight(bestSize.y);
        photo.setFullImage(false);
        photo.setMimetype("video/mp4");
        photo.setPath(videoPath);
        photo.setSize(new File(videoPath).length());
        photo.setDuration(duration);
        send(photo);
        finish();
    }

    private void send(Photo photo) {
        if (GalleryFinal.mOnCaptureListener != null)
            GalleryFinal.mOnCaptureListener.onSelected(photo);
        EventBus.getDefault().post(photo);
    }

    private void showStart() {
        rlDecide.setVisibility(View.GONE);
        rlStart.setVisibility(View.VISIBLE);
        rbClose.setVisibility(View.VISIBLE);
		tvHint.setVisibility(View.VISIBLE);
        ivChangeFlash.setVisibility(View.VISIBLE);
        ivChangeCamera.setVisibility(View.VISIBLE);
        viewSave.setVisibility(View.GONE);
    }

    public void showDecide() {
        rlDecide.setVisibility(View.VISIBLE);
        rlStart.setVisibility(View.GONE);
        rbClose.setVisibility(View.GONE);
        tvHint.setVisibility(View.GONE);
        ivChangeFlash.setVisibility(View.GONE);
        ivChangeCamera.setVisibility(View.GONE);
        if(data != null) {
            ivCutTime.setVisibility(View.GONE);
        }else {
            ivCutTime.setVisibility(View.VISIBLE);
        }
    }

    public void savePictureAsync(final byte[] data, final Camera camera) {
        new AsyncTask<Void, Void, Photo>() {

            @Override
            protected Photo doInBackground(Void... params) {
                try {
                    return savePicture(data, camera);
                } catch (IOException e) {
                    e.printStackTrace();
                }
                return null;
            }

            @Override
            protected void onPostExecute(Photo photo) {
                super.onPostExecute(photo);
                CaptureActivity.this.data = null;
                if (photo != null) {
                    send(photo);
                } else
                    Toast.makeText(CaptureActivity.this, "保存照片失败", Toast.LENGTH_SHORT).show();
                finish();
            }
        }.execute();
    }

    /**
     * 保存照片
     *
     * @param data
     * @param camera
     */
    private Photo savePicture(byte[] data, Camera camera) throws IOException {
        Bitmap bitmap = BitmapFactory.decodeByteArray(data, 0, data.length);
        Matrix matrix = new Matrix();
        matrix.postRotate(getRotateDegree(facing));
        Bitmap rotateBitmap = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), matrix, false);
        bitmap.recycle();
        Photo photo = new Photo();
        photo.setWidth(rotateBitmap.getWidth());
        photo.setHeight(rotateBitmap.getHeight());
        photo.setFullImage(false);
        photo.setMimetype("image/jpeg");

        FileOutputStream outStream = null;
        String imagePath = createPictureName();
        File file = new File(imagePath);

        outStream = new FileOutputStream(file, false);
        rotateBitmap.compress(Bitmap.CompressFormat.JPEG, 100, outStream);
        try {
            outStream.flush();
            outStream.close();
            rotateBitmap.recycle();
        } catch (IOException e) {
            e.printStackTrace();
        }
        photo.setPath(file.getAbsolutePath());
        photo.setSize(file.length());
        return photo;
    }

    /**
     * 保存图片的时候，后置摄像头需要旋转90度，前置摄像头需要旋转270度
     *
     * @param cameraId
     * @return
     */
    private int getRotateDegree(int cameraId) {
        return cameraId == Camera.CameraInfo.CAMERA_FACING_BACK ? 90 : 270;
    }

    private String createPictureName() {
        String imageUUID = UUID.randomUUID().toString().replaceAll("-", "");
        String naonaoPath = SDKUtil.IMAGE_PATH + "/" + imageUUID.substring(0, 5);
        SDKUtil.createDir(naonaoPath);
        return naonaoPath + "/" + imageUUID + ".jpg";
    }


    private boolean prepareVideoRecorder() {
        ivChangeFlash.setVisibility(View.GONE);
        ivChangeCamera.setVisibility(View.GONE);
        rbClose.setVisibility(View.GONE);
        try {
            if (mMediaRecorder != null)
                mMediaRecorder.release();
            this.mMediaRecorder = new MediaRecorder();
            this.mMediaRecorder.setOnErrorListener(new MediaRecorder.OnErrorListener() {
                @Override
                public void onError(MediaRecorder mr, int what, int extra) {
                    Log.e("录视频", "错误码：" + what);
                }
            });
            camera.unlock();
            this.mMediaRecorder.setCamera(camera);
            this.mMediaRecorder.setVideoSource(MediaRecorder.VideoSource.CAMERA);
            this.mMediaRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
            this.mMediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.MPEG_4);
            CamcorderProfile localObject = CamcorderProfile.get(CamcorderProfile.QUALITY_1080P);

            videoPath = createVideoName();
            this.mMediaRecorder.setOutputFile(videoPath);

            this.mMediaRecorder.setVideoSize(640, 480);
            this.mMediaRecorder.setAudioEncodingBitRate(44100);
            if (((CamcorderProfile) localObject).videoBitRate > 2097152)
                this.mMediaRecorder.setVideoEncodingBitRate(2097152);
            else
                this.mMediaRecorder.setVideoEncodingBitRate(((CamcorderProfile) localObject).videoBitRate);

            this.mMediaRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
            this.mMediaRecorder.setVideoEncoder(MediaRecorder.VideoEncoder.H264);
            this.mMediaRecorder.setPreviewDisplay(surfaceView.getHolder().getSurface());

            mMediaRecorder.setOrientationHint(facing == Camera.CameraInfo.CAMERA_FACING_BACK ? 90 : 270);
            this.mMediaRecorder.prepare();
            mMediaRecorder.start();
            start = System.currentTimeMillis();
        } catch (Exception localException) {
            (localException).printStackTrace();
            return false;
        }
        return true;
    }

	private void endRecord() {
		end = System.currentTimeMillis();
		long duration = end - start;
		if(duration < 4000) {
			if(mMediaRecorder != null) {
				stopRecordCopy();
				showStart();
				clearVideoFile();
			}

			Toast.makeText(getApplicationContext(),
					"视频时长不能小于3秒",
					Toast.LENGTH_SHORT)
				.show();
		}else {
			if(mMediaRecorder != null) {
				stopRecord();
			}
		}
	}

    private void stopRecord() {
        try {
            if (mMediaRecorder != null) {
                mMediaRecorder.stop();
                mMediaRecorder.release(); // release the recorder object
            }
            mMediaRecorder = null;
        } catch (Exception e) {
            e.printStackTrace();
        }
        stopPreview();
        showDecide();
        playVideo(videoPath);
    }

    private void stopRecordCopy() {
        try {
            if (mMediaRecorder != null) {
                mMediaRecorder.stop();
                mMediaRecorder.release(); // release the recorder object
            }
            mMediaRecorder = null;
        } catch (Exception e) {
            e.printStackTrace();
        }
        startPreview(cameraId, isFlash);
    }

    private void justStopRecord() {
        try {
            if (mMediaRecorder != null) {
                mMediaRecorder.stop();
                mMediaRecorder.release(); // release the recorder object
            }
            mMediaRecorder = null;
        } catch (Exception e) {
            e.printStackTrace();
        }
        stopPreview();
    }

    private void playVideo(String path) {
        try {
            mediaplayer = new MediaPlayer();
            mediaplayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
            mediaplayer.setDataSource(path);
            mediaplayer.setDisplay(surfaceView.getHolder());
            mediaplayer.setLooping(false);
            mediaplayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {

                @Override
                public void onCompletion(MediaPlayer mp) {
                    viewSave.setVisibility(View.VISIBLE);
                }
            });
            mediaplayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
                @Override
                public void onPrepared(MediaPlayer mp) {
                    mediaplayer.start();
                }
            });
            mediaplayer.prepare();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void stopVideo() {
        if (mediaplayer == null) {
            return;
        }
        try {
            if(mediaplayer.isPlaying()) {
                mediaplayer.stop();
            }
            mediaplayer.release();
            mediaplayer = null;
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private String createVideoName() {
        String videoUUID = UUID.randomUUID().toString().replaceAll("-", "");
        String naonaoPath = SDKUtil.VIDEO_PATH + "/" + videoUUID.substring(0, 5);
        SDKUtil.createDir(naonaoPath);
        return naonaoPath + "/" + videoUUID + ".mp4";
    }
}
